<?php

namespace app\home\controller;

// 引用tp的底层控制器
use think\Controller;

// 引用验证码的类
use think\captcha\Captcha;

use think\Cookie;

// 引用Db类
use think\Db;

class Index extends Controller
{
    public function __construct()
    {
        // 手动继承父级的方法
        parent::__construct();

        // 调用用户模型
        $this->UserModel = model('User.User');
        // 调用配置模型
        $this->ConfigModel = model('Config');
        $this->CateModel = model('Post.Cate');
        $this->PostModel = model('Post.Post');
        $this->CommentModel = model('Post.Comment');
        $this->RecordModel = model('User.Record');
        $SystemList = $this->ConfigModel->select();

        $System = [];

        foreach($SystemList as $item)
        {
            $System[$item['key']] = $item;
        }

        //让每个界面都可以获取系统配置
        $this->assign('System', $System);
        $this->system();
    }
    /**
     * 签到
     */ 
    public function sigin(){
        
        // var_dump($time);
        // exit;
        $success = [
            'result' => false,
            'msg' => ''
        ];
        

        if($this->request->isPost()){
            $userid = $this->request->param('userid',0);

            //判断是否登录
            if(empty($userid)){
                $success['result'] = false;
                $success['msg'] = '请登录后再签到';
                return json($success);
            }

            $userlist = $this->UserModel->where(['id'=>$userid])->find();
            // $sd = $this->LoginUser['id'];
            // var_dump($sd);
            // exit;
            $point = $userlist['point'];



            //设置cooking信息
            $LoginUser = empty(Cookie::get('LoginUser')) ? [] : Cookie::get('LoginUser');


            //获取当前用户的签到状态
            if(!empty($LoginUser)){

                $wheres = [
                    'userid' => $LoginUser['id'],
                    'state'=>4,
                ];

                //查询当前id的上一次签到情况
                $daytiem = $this->RecordModel->validate('common/User/Record')->where($wheres)->order('createtime', 'desc')->limit(1)->find();
                //签到的总次数
                $daytiemlline = $this->RecordModel->validate('common/User/Record')->where($wheres)->order('createtime', 'desc')->select();
                
                $daytype = signin($daytiem['createtime']);
                $daylinsum = signilin($daytiemlline);
                
                if($daytype){
                    $success['result'] = false;
                    $success['msg'] = '今日已签到';
                    return json($success);
                }
            }
            
            //插入消费记录表 => 更新用户表

           //开启事务
           $this->UserModel->startTrans();
           $this->RecordModel->startTrans();


           $RecordData = [
            'point' => 5,
            'state' => 4,
            'userid' => $userid,
            'content' => "每日签到获取5积分",
           ];

            //    插入消费记录表
            $RecordStatus = $this->RecordModel->validate('common/User/Record')->save($RecordData);
            
            //插入失败
            if($RecordStatus === FALSE)
            {
                //将表插入的数据回滚
        
                $this->error($this->RecordModel->getError());
                $success['result'] = false;
                $success['msg'] = '签到失败';
                return json($success);
            }

            //组装用户表数据
            $UpdatePoint = bcadd($point,5);
            $UserData = [
                'id' => $userid,
                'point' => $UpdatePoint
            ];

            //更新用户表
            $UserStatus = $this->UserModel->isUpdate(true)->save($UserData);

           //更新失败
           if($UserStatus === FALSE)
           {
               $this->RecordModel->rollback();
               $this->error($this->UserModel->getError());
               $success['result'] = false;
               $success['msg'] = '签到失败';
               return json($success);
           }

           //结束事务
           if($RecordStatus === FALSE || $UserStatus === FALSE)
           {
               $this->RecordModel->rollback();
               $this->UserModel->rollback();
               $success['result'] = false;
               $success['msg'] = '签到失败';
               return json($success);
               exit;
           } else {
               $this->RecordModel->commit();
               $this->UserModel->commit();
               $success['result'] = true;
               $success['msg'] = '签到成功';
               return json($success);
               exit;
           }


                $success['result'] = true;
                $success['msg'] = '签到成功';
            // return $time;
        }

        return json($success);
    }
    /**
     * 热议榜
     */ 
    public function hotpale()
    {

        //获取评论表信息
        // $time = signin();->field('COUNT(comment.postid) as p,comment.postid')->group('postid')->order('p desc')->limit(5)->  ->
        
        $com = $this->CommentModel->field('COUNT(postid) as p,postid')->group('postid')->order('p', 'desc')->limit(10)->select();

        // var_dump($com);

        return $com;
    }

    /**
     * 回帖榜
     */ 
    public function HotReply(){

        //获取评论表信息
        // $time = signin();->field('COUNT(comment.postid) as p,comment.postid')->group('postid')->order('p desc')->limit(5)->  ->
        
        $com = $this->CommentModel->fetchsql()->field('COUNT(pre_comment.userid) as p,pre_comment.userid,pre_user.nickname')->group('pre_comment.userid')->with('user')->select();
        // $com = $this->CommentModel->with('user')->select();
        
        var_dump($com);
        exit;
        
        return $com;

    }


     /**
     * 首页界面
     */
    public function index()
    {
        //获取热议榜信息进行首页渲染
        $comhot = $this->hotpale();

        //获取点击发布专栏的分类id
        $cateid = $this->request->param('cateid', 0);
        //帖子是否完整  
        $accept = $this->request->param('accept', '');
        //关键字搜索
        $keywords = $this->request->param('keywords', '');

        //设置cooking信息
        $LoginUser = empty(Cookie::get('LoginUser')) ? [] : Cookie::get('LoginUser');

        //获取当前用户的签到状态
        if(!empty($LoginUser)){

            $wheres = [
                'userid' => $LoginUser['id'],
                'state'=>4,
            ];

            //查询当前id的上一次签到情况
            $daytiem = $this->RecordModel->validate('common/User/Record')->where($wheres)->order('createtime', 'desc')->limit(1)->find();
            //签到的总次数
            $daytiemlline = $this->RecordModel->validate('common/User/Record')->where($wheres)->order('createtime', 'desc')->select();
            
            $daytype = signin($daytiem['createtime']);
            $daylinsum = signilin($daytiemlline);
            
        }else{
            $daytype = false;
            $daylinsum = 0;
        }


        $where = [];

        if ($accept !== '') {
            //未结
            if ($accept == 0) {
                $where['accept'] = ['exp', Db::raw('is null')];
            }
            //完结
            elseif ($accept == 1) {
                $where['accept'] = ['exp', Db::raw('is not null')];
            }
        }

        if (!empty($cateid)) {
            $where['cateid'] = $cateid;
        }
        //判断是否有关键字查询
        if (!empty($keywords)) {
            $where['title|post.content'] = ['like', "%$keywords%", 'OR'];
        }

        // 置顶
        $topList = $this->PostModel->with(['cate', 'user'])->where(['state' => 1])->order('createtime', 'desc')->limit(5)->select();

        // 文章列表 分页
        $PostList = $this->PostModel->with(['cate', 'user'])->where($where)->order('createtime', 'desc')->paginate(3);

        $reply = $this->CommentModel->field('COUNT(userid) as p,userid')->group('userid')->order('p', 'desc')->limit(6)->select();

        // 分类的
        $cateList = $this->CateModel->order('weigh', 'asc')->select();
        $this->assign([
            'cateList' => $cateList,
            'cateid' => $cateid,
            'topList' => $topList,
            'accept' => $accept,
            'PostList' => $PostList,
            'daytype' => $daytype,
            'daylinsum' => $daylinsum,
            'comhot' => $comhot,
            'reply' => $reply
        ]);
        return $this->fetch();
    }

     /**
     * 帖子详情
     */
    public function info()
    {
        // 分类id
        $cateid = $this->request->param('cateid', 0);
        //获取热议榜信息进行首页渲染
        $comhot = $this->hotpale();
        // 帖子id
        $postid = $this->request->param('postid', '');

        //查询分类列表
        $cateList = $this->CateModel->order('weigh', 'asc')->select();
        
        // 查询帖子数据
        $Post = $this->PostModel->with(['cate', 'user'])->find($postid);


        if (!$Post) {
            $this->error('该帖子不存在，请重新查看');
            exit;
        }


        // 访问量
        $visitArr = explode(',', $Post['visit']);
        $visitArr = array_filter($visitArr);
        $visitCount = is_array($visitArr) ? count($visitArr) : 0;
        //判断是否有登录
        $User = empty(cookie('LoginUser')) ? [] : cookie('LoginUser');
        $Userid = empty($User['id']) ? 0 : $User['id'];
        $User = $this->UserModel->find($Userid);

        //收藏的状态
        $CollectStatus = false;

        if ($User) {
            $collect = model('User.Collect')->where(['userid'=>$User['id'], 'postid' => $postid])->find();
            //如果查出来有，说明有收藏
            $CollectStatus = $collect ? true : false;
            if (!in_array($Userid, $visitArr)) {
                $visitArr[] = $Userid;

                $visitStr = implode(',', $visitArr);
                // 获取浏览量
                $visitCount = is_array($visitArr) ? count($visitArr) : 0;

                // 更新条件数组
                $data = [
                    'id' => $Post['id'],
                    'visit' => $visitStr
                ];

                $this->PostModel->isUpdate(true)->save($data);
            }
        }


        // 查询评论数据
        $commentList = $this->CommentModel->with(['user'])->where(['postid' => $Post['id']])->order('id', 'asc')->order('level', 'asc')->select();

        $commentList = CommentTree($commentList, 0, $User);

        // 输出数组
        // halt(collection($commentList)->toArray());




        $this->assign([
            'cateid' => $cateid,
            'cateList' => $cateList,
            'Post' => $Post,
            'CollectStatus' => $CollectStatus,
            'visitCount' => $visitCount, //访问量
            'commentList' => $commentList,   //评论列表
            'comhot' => $comhot,  //热议榜
        ]);

        return $this->fetch();
    }

     /**
     * 注册界面
     */
    public function register()
    {
        // 获取cookie
        $LoginUser = cookie('LoginUser');

        if (!empty($LoginUser)) {
            $id = isset($LoginUser['id']) ? $LoginUser['id'] : 0;

            $User = $this->UserModel->where(['id' => $id])->find();

            if ($User) {
                $this->success('你已登录，无须重新注册', 'home/user/index');
                exit;
            }
        }
        // 判断是否有post提交
        if ($this->request->isPost()) // $_POST
        {
            // 接收验证码 
            $vercode = $this->request->post('vercode', ''); // $_POST['vercode']

            // 判断验证码是否正确
            if (!captcha_check($vercode)) {
                $this->error('验证码输入错误，请重新输入');
                exit;
            }

            // 接收邮箱
            $email = $this->request->param('email', ''); // POST和GET方法


            // 生成10位随机字符串
            $salt = build_ranstr(10);

            // 接收密码
            $pass = $this->request->param('pass', '');

            // 接收确认密码
            $repass = $this->request->param('repass', '');

            // 接收昵称
            $nickname = $this->request->param('nickname', '');

            // 查询数据表是否存在该昵称 暂时不用做

            if ($pass != $repass) {
                $this->error('密码不一致，请重新输入');
                exit;
            }

            // 加密
            $password = md5($pass . $salt);

            // 获取注册赠送的积分
            $RegPoint = $this->ConfigModel->where(['key' => 'RegisterPoint'])->value('value');

            $RegPoint = is_numeric($RegPoint) ? abs($RegPoint) : 0;

            // 封装插入数据的数组
            $data = [
                'email' => $email,
                'password' => $password,
                'salt' => $salt,
                'nickname' => $nickname,
                'point' => $RegPoint,
                'sex' => 0,
                'vip' => 0,
                'auth' => 0
            ];

            // 插入数据表
            $result = $this->UserModel->validate('common/User/User')->save($data);

            if ($result === FALSE) {
                $this->error($this->UserModel->getError());
                exit;
            } else {
                $this->success('注册成功', url('home/index/login'));
                exit;
            }
        }
        return $this->fetch();
    }

    /**
     * 登录界面
     */
    public function login()
    {
        // 获取cookie
        $LoginUser = cookie('LoginUser');

        if (!empty($LoginUser)) {
            $id = $LoginUser['id'];

            $User = $this->UserModel->where(['id' => $id])->find();

            if ($User) {
                $this->success('你已登录，无须重新登录', 'home/user/index');
                exit;
            }
        }
        if ($this->request->isPost()) {
            // 接收邮箱
            $email = $this->request->param('email', '');
            // 接收验证码
            $vercode = $this->request->param('vercode', '');
            // 密码
            $pass = $this->request->param('pass', '');

            if (!captcha_check($vercode)) {
                $this->error('验证码输入错误，请重新输入');
                exit;
            }

            $User = $this->UserModel->where(['email' => $email])->find();

            if (!$User) {
                $this->error('邮箱不存在，请重新输入');
                exit;
            }

            // 获取密码盐
            $salt = $User['salt'];

            // 加密
            $password = md5($pass . $salt);

            if ($password != $User['password']) {
                $this->error('密码错误，请重新输入');
                exit;
            }

            // 封装用户信息 存入cookie
            $data = [
                'id' => $User['id'],
                'nickname' => $User['nickname'],
                'email' => $User['email'],
                'vip' => $User['vip'],
                'auth' => $User['auth'],
                // isset => null 
                'avatar' => !empty($User['avatar']) ? $User['avatar'] : '/static/home/res/images/avatar/default.png',
                'cover' => !empty($User['cover']) ? $User['cover'] : '/static/home/res/images/cover.jpg'
            ];

            cookie('LoginUser', $data);

            $this->success('登录成功', url('home/index/index'));
            exit;
        }

        return $this->fetch();
    }

    /**
     * 退出界面
     */
    public function logout()
    {
        cookie('LoginUser', null);
        $this->success('退出成功', url('home/index/index'));
        exit;
    }

    /**
     * 邮箱验证
     * 验证邮件发送成功并且点击认证的处理方法
     **/ 
    public function email()
    {
        // 接收加密邮箱
        $email = $this->request->param('email', '');
        // echo $email;
        if (empty($email)) {
            $this->error('邮箱为空，请重新登录', url('home/index/login'));
            exit;
        }


        $User = $this->UserModel->field('id,email')->select();

        // 定义空的变量
        $userid = '';
        // dump($User);
        foreach ($User as $item) {
            // 把所有的用户邮箱进行加密
            $Email = md5($item['email']);
            // 判断接收的邮箱跟数据表的邮箱是否有匹配
            if ($email == $Email) {
                $userid = $item['id'];
                break;
            }
        }

        // echo $userid;
        // 封装更新数据的数组
        $data = [
            'id' => $userid,
            'auth' => 1
        ];

        $result = $this->UserModel->isUpdate(true)->save($data);

        $user = $this->UserModel->find($userid);

        $data = [
            'id' => $user['id'],
            'nickname' => $user['nickname'],
            'email' => $user['email'],
            'vip' => $user['vip'],
            'auth' => $user['auth'],
            // isset => null 
            'avatar' => !empty($user['avatar']) ? $user['avatar'] : '/static/home/res/images/avatar/default.png',
            'cover' => !empty($user['cover']) ? $user['cover'] : '/static/home/res/images/cover.jpg'
        ];

        // 认证成功后
        cookie('LoginUser', $data);

        if ($result === FALSE) {
            $this->error('验证失败', url('home/user/profile'));
            exit;
        } else {
            $this->success('验证成功', url('home/user/profile'));
            exit;
        }
    }

    /**
     * 验证码
     **/
    public function captcha()
    {
        $config = [
            'length' => 4,
            'imageW' => 120,
            'imageH' => 40,
            'fontSize' => 18
        ];

        $captcha = new Captcha($config);
        return $captcha->entry();
    }

    public function system()
    {
        $SystemList = $this->ConfigModel->select();
        // halt($SystemList);

        // 定义一个空数组
        $System = [];

        foreach ($SystemList as $key => $item) {
            $System[$item['key']] = $item['value'];
        }

        // 赋值给所有的视图
        $this->assign('System', $System);
    }

    
}
